import os
from prettytable import PrettyTable
from gofishing.base import Base
from gofishing.commodity import CommodityBase
from gofishing.indicator import Indicator
from gofishing.broker import Broker
from gofishing.strategy import Strategy
from gofishing.observer import ObserverBase


class Fishing:

    def start(board=True) -> None:
        while Base.update():
            CommodityBase.update()
            Indicator.update()
            Broker.update()
            Strategy.update()
            ObserverBase.update()
            if board:
                Fishing.boardUpdate()

    def boardUpdate() -> None:
        accountTable = PrettyTable([
            'STATV', 'FRMARG', 'FRCOMM', 'FPROFIT',
            'VALUE', 'MARGIN', 'AVAIL', 'RISKR'])
        accountTable.float_format = '.2'
        accountValues = Broker.getAccountValues()
        accountTable.add_row([
            accountValues.staticValue, accountValues.frozenMargin,
            accountValues.frozenCommission, accountValues.floatingProfit,
            accountValues.value, accountValues.margin,
            accountValues.available, accountValues.riskRatio])

        holdingTable = PrettyTable(
            ['STRATID', 'COMID', 'CODE', 'LONG', 'SHORT',
             'LONGOP', 'SHORTOP', 'CLOSE'])
        holdingTable.float_format = '.2'
        strategies = Strategy.strategies
        for strategyID in strategies:
            strategy: Strategy = strategies[strategyID]
            commodity = strategy.commodity
            holdingTable.add_row([
                strategy.stratID,
                commodity.commodityID, commodity.contractCode,
                strategy.long, strategy.short,
                strategy.longOpenPrice, strategy.shortOpenPrice,
                commodity.close[-1]])

        orderTable = PrettyTable(
            ['STRATID', 'COMID', 'CODE', 'TYPE', 'LIMITP', 'VOL', 'INSERT'])
        orderTable.float_format = '.2'
        strategies = Strategy.strategies
        for strategyID in strategies:
            strategy: Strategy = strategies[strategyID]
            commodity = strategy.commodity
            for orderID in strategy.orderIDs:
                orderInfo = Broker.getOrderInfo(orderID=orderID)
                orderTable.add_row([
                    strategy.stratID,
                    commodity.commodityID, commodity.contractCode,
                    orderInfo.tradeType.value, orderInfo.limitPrice,
                    '%d/%d' % (orderInfo.volumeLeft, orderInfo.volume),
                    orderInfo.insertTime.isoformat(sep=' ')])

        time = 'Updated time: ' + Base.now().isoformat(sep=' ')
        board = time + \
            '\n' + accountTable.get_string() + \
            '\n' + holdingTable.get_string() + \
            '\n' + orderTable.get_string()
        Fishing._clearScreen()
        print(board)

    def _clearScreen() -> None:
        if os.name == 'posix':
            _ = os.system('clear')
        else:
            _ = os.system('cls')
